﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QInputDialog>
#include <QMessageBox>
#include <QString>
#include <QWidget>
#include <QStyle>
#include <QScreen>
#include <QApplication>
#include <QDesktopWidget>
#include <QStyle>
#include <QFile>
#include <QTextStream>
#include <QTableWidgetItem>
#include "../../thread/UDPSocketThread.h"
#include "../../thread/ReceiveThread.h"
#include "MessageHelper.h"
#include "User.h"

User user;
extern UDPSocketThread* udpSocketThread;
extern ReceiveThread* recvThread;
extern MsgQueue queue_send;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<"工单号"<<"会议主题"<<"时间");

    QString text = QStringLiteral("尊敬的%1您好,这是历史工单").arg(QString(user.username));
    ui->label_2->setText(text);

    
    setWindowTitle("日上会议");
    
    roomHandler = new RoomHandler(nullptr, this);
    historyHandler = new HistoryHandler(this);

    inviteExpert = new InviteExpert(roomHandler);
    roomHandler->setInviteWindow(inviteExpert);

    connect(recvThread, &ReceiveThread::recvCreated, roomHandler, &RoomHandler::joinRoomAfterCreate);
    connect(recvThread, &ReceiveThread::recvJoined, this, &MainWindow::createVideoRoom);
    connect(recvThread, &ReceiveThread::recvExpertsMsg, inviteExpert, &InviteExpert::recvExperts);
    connect(recvThread, &ReceiveThread::recvInvitationMsg, inviteExpert, &InviteExpert::recvInvitation);

    if(user.userType == 1){
        ui->pushButton_joinRoom->setText("查看邀请");
    } 
}

MainWindow::~MainWindow() {
    delete ui;
    delete inviteExpert;
}

void MainWindow::createVideoRoom(const quint16& roomId, const QList<quint16>& partnerList) {
    this->hide();
    if (!videoroom)
        videoroom = std::make_unique<Videoroom>(roomId, partnerList);
    videoroom->show();

    connect(videoroom.get(), &Videoroom::backToMainClicked, [this](){
        videoroom.reset();
        this->showMain();
    });

    connect(videoroom->cameraHandler, &CameraHandler::pushImg, videoroom.get(), &Videoroom::onNewFrame);
    connect(recvThread, &ReceiveThread::recvImg, videoroom.get(), &Videoroom::recvNewFrame);
    connect(recvThread, &ReceiveThread::recvText, videoroom.get(), &Videoroom::recvNewText);
    connect(recvThread, &ReceiveThread::recvAudio, videoroom->getAudio()->audioOutput, &AudioOutput::playData);
    connect(recvThread, &ReceiveThread::recvNewPartner, videoroom.get(), &Videoroom::addPartner);
}

//点击加入房间按钮
void MainWindow::on_toolButton_createRoom_clicked() {
    this->hide();
    if (!joinroom)
        joinroom = std::make_unique<Joinroom>();
    joinroom->show();
    connect(joinroom.get(), &Joinroom::backToMainClicked, [this](){
        joinroom.reset();
        this->showMain();
    });
    connect(joinroom.get(), &Joinroom::inputConfirmed, [this](quint16 roomId){
        roomHandler->joinRoom(roomId);
        joinroom->hide();
    });
}

void MainWindow::on_pushButton_me_clicked()
{
    this->hide();
    if (!mewindow)
        mewindow = std::make_unique<Mewindow>();
    mewindow->show();
    mewindow->adjustSize();

    connect(mewindow.get(), &Mewindow::back, [this](){
        mewindow.reset();
        this->showMain();
    });
}

void MainWindow::showMain() {
    this->show();
    this->raise();
    this->activateWindow();
}
void MainWindow::showEvent(QShowEvent *event) {
    // 每次 show 都重新居中
    setGeometry(
        QStyle::alignedRect(
            Qt::LeftToRight,
            Qt::AlignCenter,
            size(),
            qApp->primaryScreen()->availableGeometry()
        )
    );
    loadCsvToTable(QApplication::applicationDirPath() + "/userImformation/history.txt");    //历史工单的文件路径
    QMainWindow::showEvent(event);
}

//点击创建房间按钮（如果是专家号，会显示成查看邀请）
void MainWindow::on_pushButton_joinRoom_clicked() {
    this->hide();

    if(user.userType == 0){
        roomHandler->createRoom();
    } else {
        MSG msg;
        msg.type = MSG::QUERY;
        msg.data = "INVITATION";
        queue_send.push_back(msg);
        inviteExpert->show();
    }
}

//显示历史工单的函数
void MainWindow::loadCsvToTable(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        //QMessageBox::warning(this, "提示", "无法打开文件：" + filePath);
        return;
    }

    ui->tableWidget->setRowCount(0);   // 先清空旧数据
    QTextStream in(&file);
    in.setCodec("UTF-8");

    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList columns = line.split(',', QString::KeepEmptyParts);
        if (columns.size() != 3) continue;   // 跳过格式不对的行

        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);

        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(columns[0])); // 工单号
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(columns[1])); // 会议主题
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(columns[2])); // 时间
    }
    file.close();
}
